<template>
    <div class="edit">
        <!-- 顶部导航 -->
        <van-nav-bar
            title="个人信息"
            left-arrow
            @click-left="$router.go(-1)"
            right-text="编辑"
            @click-right="isShowEditInput = true"
        ></van-nav-bar>

        <!-- 用户昵称输入框 -->
        <van-field
            label="用户昵称"
            v-model="user.nickname"
            :readonly="!isShowEditInput"
        ></van-field>

        <!-- 提交按钮 -->
        <van-button type="primary" block v-show="isShowEditInput" @click="save"
            >保存</van-button
        >
    </div>
</template>

<script>
export default {
    data() {
        return {
            isShowEditInput: false,
            user: JSON.parse(window.sessionStorage.getItem("user"))
        };
    },
    methods: {
        async save() {
            const res = await this.$http.put("/users", {
                nickname: this.user.nickname
            });
            if (res.code !== 200) {
                this.$toast({
                    type: "fail",
                    message: res.message
                });
                return;
            }
            // 修改成功
            this.$toast({
                type: "success",
                message: "修改成功"
            });
            // 改成只读状态
            this.isShowEditInput = false;
        }
    }
};
</script>

<style lang="less">
.edit {
    .van-field,
    .van-button {
        margin-top: 10px;
    }
}
</style>
